package com.kgis.fm.business.management.service.impl.support;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 解析stylerule与labelrule的filter，将sql语法转换成flex客户端支持的语法格式
 * @author zhxiaomiao
 *
 */
public class SQLRuleParseSupport {
	private static final transient Log log = LogFactory.getLog(SQLRuleParseSupport.class);
	
	public static String SQLRuleFlexParse(String input){
		String outPut = "";
		if(input ==null || input.equals(""))
			return "";
		if(log.isDebugEnabled()){
			log.debug("sqlRule's input:"+input);
		}
		//处理类似1AND--》1 AND，1or-->1 OR
		input=input.toUpperCase();
		Pattern pattern = Pattern.compile("[^a-zA-Z_ ]AND ");
		Matcher matcher = pattern.matcher(input);
		StringBuffer stbf=new StringBuffer(input);		
		int start = 0;
		while (matcher.find(start)) {
			int idx = stbf.indexOf(matcher.group())+1;
			start = idx;
			stbf.insert(idx, " ");
			
		}		
		input= stbf.toString();
		
		String mid = input.trim().replaceAll(" +", " ").replaceAll("=+", "=")
					.replaceAll(" AND", " and").replaceAll(" OR", " or").replaceAll(" IN", " in");
		if(!mid.contains("in")){
			outPut=mid.trim();
			if(log.isDebugEnabled()){
				log.debug("sqlRule's outPut:"+outPut);
			}
			return mid.trim().replaceAll("=", "==");
		}
		String[] inArray = mid.split("in");
		
		String inConditon = "";
		String str = inArray[0].trim();
		if (str.contains("and") || str.contains("or")) {
			// 说明in不是第一个条件
			outPut = str.substring(0, str.lastIndexOf(" ")) + " (";
			inConditon = str.substring(str.lastIndexOf(" "), str.length());
		} else {
			// in为第一个条件
			outPut="(";
			inConditon = str;
		}
		for (int i = 1; i < inArray.length; i++) {
			String midStr = inArray[i].trim();
			String valueCondition = "";
			valueCondition = midStr.substring(midStr.indexOf("(") + 1, midStr.indexOf(")")).trim();
			String[] suffixInArray = valueCondition.split(",");
			String value = "";
			for (int k = 0; k < suffixInArray.length; k++) {
				value = inConditon + " = " + suffixInArray[k];
				if (k != suffixInArray.length - 1) {
					value = value + " or ";
				}
				outPut = outPut.concat(value);
			}
			outPut = outPut + ") ";
			
			//取下一个条件
			String temp=midStr.substring(midStr.indexOf(")")+1,midStr.length()).trim();
			if(temp.contains("and") || temp.contains("or")){
				//中间值，不能为最后一个
				if(i!=inArray.length-1){
					outPut=outPut.concat(temp.substring(0, temp.lastIndexOf(" ")))+" (";
					inConditon=temp.substring(temp.lastIndexOf(" ")+1,temp.length()).trim();
				}else{
					outPut=outPut.concat(temp);
				}
			}
		}
		if(log.isDebugEnabled()){
			log.debug("sqlRule's outPut:"+outPut);
		}
		return outPut.trim().replaceAll("=", "==");
	}
}
